import re

from django_redis import get_redis_connection
from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from question.models import Respond, Troubles
from users.models import User, Archives


class CreateUserSerializer(ModelSerializer):
    """定义用户注册序列化器"""

    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        """检验用户是否同意协议"""
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate(self, data):
        # 判断短信验证码
        redis_conn = get_redis_connection('verify_code')
        mobile = data['mobile']
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError('无效的短信验证码')
        if data['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return data

    def create(self, validated_data):
        """
        创建用户
        """
        # 移除数据库模型类中不存在的属性
        del validated_data['sms_code']
        del validated_data['allow']

        # 调用父类的create方法去保存用户的信息
        user = super().create(validated_data)

        # 调用django的认证系统加密密码
        user.set_password(validated_data['password'])
        user.save()

        # 生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 给user对象添加token属性
        user.token = token

        return user


class AvatarSerializer(serializers.ModelSerializer):
    """用户头像序列化器"""

    class Meta:
        model = User
        fields = ['avatar']


class UserDetailSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'avatar', 'intro', 'city', 'school', 'company', 'website', 'position', 'specialities', 'email')


class UserQuestionsserializer(serializers.ModelSerializer):
    """我的提问序列化器"""
    class Meta:
        model = Troubles
        fields = ('title', 'like_count')


class UserAnswerserializer(serializers.ModelSerializer):
    """我的回答序列化器"""
    class Meta:
        model = Troubles
        fields = ('title', 'like_count')


class UserDataSerializer(serializers.ModelSerializer):
    """用户资料序列化器"""

    class Meta:
        model = User
        fields = ['username', 'mobile', 'email', 'website']


class UserPWDSerializer(serializers.ModelSerializer):
    """修改密码"""
    password1 = serializers.CharField(max_length=28, min_length=8, write_only=True)

    class Meta:
        model = User
        fields = ['password', 'password1']

    def validate_password(self, value):
        user = self.instance
        if user.check_password(value):
            return value

        raise serializers.ValidationError("原密码验证错误")

    def update(self, instance, validated_data):
        user = instance
        password = validated_data['password1']
        user.set_password(password)
        user.save()

        return user


class UserArchivesserializer(serializers.ModelSerializer):
    """用户档案"""
    user = UserDataSerializer(read_only=True)

    class Meta:
        model = Archives
        fields = "__all__"
